<template>
  <div class="chat-container">
    <!-- 头部导航 -->
    <div class="chat-header">
      <button class="back-btn" @click="goBack">
        ← 返回
      </button>
      <h2 class="chat-title">
        💕 AI恋爱大师
      </h2>
      <div class="chat-status">
        <span :class="['status-dot', { 'online': isConnected }]"></span>
        {{ isConnected ? '在线' : '离线' }}
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div class="welcome-message" v-if="messages.length === 0">
        <div class="welcome-icon">💕</div>
        <h3>欢迎来到AI恋爱大师</h3>
        <p>我是您的专属恋爱顾问，可以为您提供情感建议和恋爱指导。请告诉我您遇到的问题吧！</p>
      </div>
      
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message', message.type]"
      >
        <div class="message-avatar">
          <span v-if="message.type === 'user'">👤</span>
          <span v-else>💕</span>
        </div>
        <div class="message-content">
          <div class="message-text" v-html="formatMessage(message.content)"></div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
      
      <!-- 正在输入指示器 -->
      <div v-if="isTyping" class="message ai typing">
        <div class="message-avatar">
          <span>💕</span>
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-container">
        <textarea 
          v-model="inputMessage"
          @keydown.enter.prevent="sendMessage"
          @input="adjustTextareaHeight"
          placeholder="请输入您的问题..."
          class="message-input"
          ref="messageInput"
          :disabled="isLoading"
        ></textarea>
        <button 
          @click="sendMessage" 
          :disabled="!inputMessage.trim() || isLoading"
          class="send-btn"
        >
          <span v-if="isLoading">发送中...</span>
          <span v-else>发送</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { chatWithLoveApp } from '../services/api'

export default {
  name: 'LoveChat',
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      isTyping: false,
      isConnected: false,
      chatId: '',
      currentConnection: null,
      typewriterQueue: [], // 打字机效果队列
      isTypewriting: false, // 是否正在执行打字机效果
      typewriterTimer: null, // 打字机定时器引用
      lastSendTime: 0 // 上次发送消息的时间戳
    }
  },
  mounted() {
    this.generateChatId()
    this.focusInput()
  },
  beforeUnmount() {
    this.closeConnection()
    this.clearTypewriterEffect()
  },
  methods: {
    generateChatId() {
      // 生成唯一的聊天室ID
      this.chatId = 'love_chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
    },
    
    goBack() {
      this.$router.push('/')
    },
    
    focusInput() {
      this.$nextTick(() => {
        if (this.$refs.messageInput) {
          this.$refs.messageInput.focus()
        }
      })
    },
    
    adjustTextareaHeight() {
      const textarea = this.$refs.messageInput
      if (textarea) {
        textarea.style.height = 'auto'
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
      }
    },
    
    sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      // 防抖机制：限制发送频率（最少间隔1秒）
      const now = Date.now()
      if (now - this.lastSendTime < 1000) {
        console.warn('发送频率过快，请稍后再试')
        return
      }
      this.lastSendTime = now
      
      // 如果已有连接在进行中，先关闭
      if (this.currentConnection) {
        this.closeConnection()
      }
      
      const userMessage = {
        type: 'user',
        content: this.inputMessage.trim(),
        timestamp: new Date()
      }
      
      this.messages.push(userMessage)
      const messageToSend = this.inputMessage.trim()
      this.inputMessage = ''
      this.isLoading = true
      this.isTyping = true
      
      // 重置输入框高度
      this.$nextTick(() => {
        if (this.$refs.messageInput) {
          this.$refs.messageInput.style.height = 'auto'
        }
      })
      
      this.scrollToBottom()
      
      // 创建AI消息对象
      const aiMessage = {
        type: 'ai',
        content: '',
        timestamp: new Date()
      }
      
      // 建立SSE连接
      this.currentConnection = chatWithLoveApp(
        messageToSend,
        this.chatId,
        (data) => {
          // 收到消息
          this.isConnected = true
          this.isTyping = false
          
          if (!this.messages.includes(aiMessage)) {
            this.messages.push(aiMessage)
          }
          
          // 使用打字机效果逐字显示消息
          this.typewriterEffect(aiMessage, data)
        },
        (error) => {
          // 连接错误
          console.error('SSE连接错误:', error)
          this.isConnected = false
          this.isLoading = false
          this.isTyping = false
          
          if (!this.messages.includes(aiMessage)) {
            this.messages.push({
              type: 'ai',
              content: '抱歉，连接出现问题，请稍后重试。',
              timestamp: new Date()
            })
          }
          this.scrollToBottom()
        },
        () => {
          // 连接关闭
          this.isConnected = false
          this.isLoading = false
          this.isTyping = false
          this.currentConnection = null
        }
      )
      
      // 注意：不要重复设置事件监听器，避免死循环
      // EventSource的事件监听已在createSSEConnection中处理
    },
    
    closeConnection() {
      if (this.currentConnection) {
        this.currentConnection.close()
        this.currentConnection = null
      }
    },
    
    clearTypewriterEffect() {
      if (this.typewriterTimer) {
        clearInterval(this.typewriterTimer)
        this.typewriterTimer = null
      }
      this.typewriterQueue = []
      this.isTypewriting = false
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },
    
    formatMessage(content) {
      // 简单的文本格式化，将换行符转换为<br>
      return content.replace(/\n/g, '<br>')
    },
    
    formatTime(timestamp) {
      return timestamp.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    // 打字机效果：逐字显示消息内容
    typewriterEffect(messageObj, newContent) {
      // 如果新内容为空，直接返回
      if (!newContent) return
      
      // 将新内容添加到队列
      this.typewriterQueue.push({ messageObj, content: newContent })
      
      // 如果当前没有在执行打字机效果，开始处理队列
      if (!this.isTypewriting) {
        this.processTypewriterQueue()
      }
    },
    
    // 处理打字机效果队列
    processTypewriterQueue() {
      if (this.typewriterQueue.length === 0) {
        this.isTypewriting = false
        return
      }
      
      this.isTypewriting = true
      const { messageObj, content } = this.typewriterQueue.shift()
      
      // 逐字添加内容
       let index = 0
       this.typewriterTimer = setInterval(() => {
         if (index < content.length) {
           messageObj.content += content[index]
           this.scrollToBottom()
           index++
         } else {
           clearInterval(this.typewriterTimer)
           this.typewriterTimer = null
           // 继续处理队列中的下一个内容
           this.processTypewriterQueue()
         }
       }, 20) // 每20ms显示一个字符，提供流畅的打字效果
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
}

.chat-header {
  background: rgba(255, 255, 255, 0.95);
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  backdrop-filter: blur(10px);
}

.back-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  color: #666;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(255, 105, 135, 0.1);
  color: #ff6987;
}

.chat-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.chat-status {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
  color: #666;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
  transition: all 0.3s ease;
}

.status-dot.online {
  background: #4CAF50;
  box-shadow: 0 0 8px rgba(76, 175, 80, 0.5);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
  color: rgba(255, 255, 255, 0.9);
}

.welcome-icon {
  font-size: 3rem;
  margin-bottom: 15px;
}

.welcome-message h3 {
  font-size: 1.5rem;
  margin-bottom: 10px;
  color: white;
}

.welcome-message p {
  font-size: 1rem;
  line-height: 1.6;
  max-width: 500px;
  margin: 0 auto;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.ai {
  align-self: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  flex-shrink: 0;
}

.message.user .message-avatar {
  background: linear-gradient(45deg, #667eea, #764ba2);
}

.message.ai .message-avatar {
  background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
}

.message-content {
  flex: 1;
}

.message-text {
  background: rgba(255, 255, 255, 0.95);
  padding: 12px 16px;
  border-radius: 18px;
  line-height: 1.5;
  word-wrap: break-word;
  backdrop-filter: blur(10px);
}

.message.user .message-text {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
}

.message-time {
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 5px;
  text-align: right;
}

.message.ai .message-time {
  text-align: left;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 18px;
  backdrop-filter: blur(10px);
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff6987;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.chat-input {
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  min-height: 44px;
  max-height: 120px;
  padding: 12px 16px;
  border: 2px solid rgba(255, 105, 135, 0.2);
  border-radius: 22px;
  font-size: 16px;
  resize: none;
  outline: none;
  transition: all 0.3s ease;
  font-family: inherit;
}

.message-input:focus {
  border-color: #ff6987;
  box-shadow: 0 0 0 3px rgba(255, 105, 135, 0.1);
}

.message-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-btn {
  background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.send-btn:hover:not(:disabled) {
  background: linear-gradient(45deg, #ff5252, #ff7979);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-header {
    padding: 12px 15px;
  }
  
  .chat-title {
    font-size: 1.1rem;
  }
  
  .chat-messages {
    padding: 15px;
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-input {
    padding: 15px;
  }
}
</style>